﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Freejobber.Core.Generic.Security;
using Freejobber.Core.Generic;
using Freejobber.Core.Generic.Profile;

namespace Freejobber.Modules.Login
{
    public partial class LoginControl : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
                if (IsPostBack)
                    if (Validate() == "validated") //Проверка правил логина и пароля.
                        TryAuthUser();
            if (SecurityManager.IsUserLogon())
            {
                UserClass _user=SecurityManager.GetCurrentUser();
                divLogin.Visible = false;
                divUserInfo.Visible = true;
                hlLoginName.Text = _user.UserName;
                hlLoginName.NavigateUrl = string.Format("{0}",ConfigManager.ProfilePageUrl);
                lblFullname.Text = _user.UserName;
               // ByteImage.InitUserImage(_user.LoginName);
            }
            else
            {
                divLogin.Visible = true;
                divUserInfo.Visible = false;

            }

        }

        /// <summary>
        /// Попытка входа
        /// </summary>
        private void TryAuthUser()
        {
            string _userLogin = "";
            string _userPassword = "";
            _userLogin = Server.HtmlEncode(tbLogin.Text);
            _userPassword = Server.HtmlEncode(tbPassword.Text);
            if (SecurityManager.UserLogin(_userLogin, _userPassword))
            {

            }
        }


        /// <summary>
        /// Список правил валидации
        /// </summary>
        /// <returns></returns>
        private new string Validate()
        {
            string result = string.Empty;

            if (string.IsNullOrEmpty(tbLogin.Text) || string.IsNullOrEmpty(tbPassword.Text))
            {
                result = "Логин или пароль пуст.";
            }
            else if (tbLogin.Text.Count() < 3)
            {
                result = "Логин слишком короткий.";
            }
            else
            {
                result = "validated"; //Все OK.
            }
            return result;
        }
    }
}